from django.db import models
from django.utils.timezone import now
from django.conf import settings


# Create your models here.
class BaseModel(models.Model):
    aid = models.AutoField(primary_key=True)
    createdAt = models.DateTimeField('创建时间', default=now)
    updatedAt = models.DateTimeField('修改时间', default=now)

    class Meta:
        abstract = True


class Article(BaseModel):
    A_STATUS = (
        ('D', "草稿"),
        ('P', "发表")
    )
    C_STATUS = (
        ('O', "开启"),
        ('C', "关闭")
    )
    title = models.CharField("标题", max_length=100)
    abstract = models.CharField("摘要", max_length=200)
    body = models.TextField("正文", max_length=5000)
    author = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        verbose_name='作者',
        blank=False,
        null=False,
        on_delete=models.CASCADE    # 级联删除
    )
    updatedAt = models.DateTimeField(
        "更新时间",
        blank=False,
        null=False,
        default=now
    )
    status = models.CharField(
        "文章状态",
        choices=A_STATUS, default='P',
        max_length=1
    )

    def __str__(self):
        return self.title

    class Meta:
        ordering = ['updatedAt']
        verbose_name = "文章"
        verbose_name_plural = verbose_name


class Tag(models.Model):
    tag_id = models.AutoField(primary_key=True)
    content = models.CharField("标签内容", max_length=30, unique=True)

    class Meta:
        verbose_name = "标签"
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.content


# 多对多关系中间表
class Article2Tags(models.Model):
    atid = models.AutoField(primary_key=True)
    article = models.ForeignKey(
        Article,
        verbose_name='文章',
        on_delete=models.CASCADE
    )
    tag = models.ForeignKey(
        Tag,
        verbose_name='tag',
        on_delete=models.CASCADE
    )

    class Meta:
        verbose_name = "文章-tag中间表"
        verbose_name_plural = verbose_name

    def __str__(self):
        ret = str(self.article.title) + ' -- ' + str(self.tag.content)
        return ret
